package com.example.base_kotlin_xml.model

import androidx.lifecycle.viewModelScope
import com.example.base_model.bean.general.UserInfo
import com.example.base_model.mvvm.BaseViewModel
import com.example.base_model.network.load.LoadingStrategy
import com.example.base_model.network.load.LoadingUiState
import com.example.base_model.network.request_param.BeanParamInterface
import com.example.base_model.network.result.BaseResult
import com.example.base_model.sp.DataStoreManager
import com.example.base_model.sp.management_keys.AppPreferenceKey
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

/**
 * @Author jiangKunKun
 * @CreateDate 2025/8/6
 * @Description
 * @SpittingGrooves
 */
data class DatastoreUiState(
    override val loadingGroups: Map<LoadingStrategy, Int> = emptyMap(),
    val saveResult: BaseResult<Unit> = BaseResult.IDLE(),
    val userInfoResult: BaseResult<UserInfo?> = BaseResult.IDLE(),
    val clearResult: BaseResult<Unit> = BaseResult.IDLE()
) : LoadingUiState {
    override fun copyWithLoading(groups: Map<LoadingStrategy, Int>): LoadingUiState {
        return this.copy(loadingGroups = groups)
    }
}

@HiltViewModel
class DatastoreViewModel @Inject constructor(
    val dataStoreManager : DataStoreManager
): BaseViewModel() {

    val userInfoFlow: StateFlow<UserInfo?> =
        dataStoreManager.readObject<UserInfo>(AppPreferenceKey.USER_INFO)
            .map<UserInfo?, UserInfo?> { it } // 直接映射 Flow<UserInfo?> 到 Flow<UiResult<UserInfo?>>
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5000), // 当有订阅者时开始，5秒后停止
                initialValue = null // 初始值
            )
    private val _uiState = MutableStateFlow(DatastoreUiState())
    val uiState: StateFlow<DatastoreUiState> = _uiState.asStateFlow()
    /**
     * 保存完整用户信息
     */
    fun saveUserInfo(userInfo: UserInfo) {
        launchLocWithStateFlow(
            stateFlow = _uiState,
            stateUpdateBlock = { state, result -> state.copy(saveResult = result) },
            block = { dataStoreManager.saveObject(AppPreferenceKey.USER_INFO, userInfo) },
            requestParam = BeanParamInterface(userInfo)
        )
    }

    /**
     * 读取完整用户信息 (一次性命令)
     */
    fun loadUserInfo() {
        launchLocWithStateFlow(
            stateFlow = _uiState,
            loadingStrategy = LoadingStrategy.MAIN, // 例如，加载时显示对话框
            stateUpdateBlock = { state, result -> state.copy(userInfoResult = result) },
            block = { dataStoreManager.readObject<UserInfo>(AppPreferenceKey.USER_INFO).firstOrNull() },
            transform = {
                it.apply {
                    it?.name = "修改后的名字"
                    it?.age = 789456123
                }
            }
        )
    }

    /**
     * 清除设备信息
     */
    fun clearDeviceInfo() {
        launchLocWithStateFlow(
            stateFlow = _uiState,
            stateUpdateBlock = { state, result -> state.copy(clearResult = result) },
            block = { dataStoreManager.removeObject(AppPreferenceKey.USER_INFO) }
        )
    }

}